
import VueRouter from 'vue-router'
import { tokenStorage } from '~/utils/storage'
import 'amfe-flexible/index.js'
const whiteList = ["/sign/login","/sign/register","/sign/forget","/home","/market","/ticker"] // no redirect whitelist
export default ({ app }) => {
  app.router.beforeEach(async(to, from, next) => {
    let transitionName = ''
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    if (toDepth > fromDepth) {
      transitionName = 'slide-left'
    } else if (toDepth < fromDepth) {
      transitionName = 'slide-right'
    } else {
      transitionName = 'page'
    }
    app.store.dispatch('setTransitionName', transitionName)

    if (!app.store.state.initInfo || !Object.keys(app.store.state.initInfo).length > 0) {
      app.store.dispatch('getInitInfo')
    }
    const accessToken = tokenStorage.get() || ''
    next() 
    if (accessToken) {
      if (!app.store.state.user.logged) {
        try {
           await app.store.dispatch('user/getUserInfo')
           await app.store.dispatch('robot/robotList')
          next({ ...to, replace: true })
        } catch (error) {
          next(`/sign/login`)
        }
      }else{
        next()
      }
    }else{
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next({path:'/sign/login'})
      }
    }
  })
}

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location)
}
